﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SparkBench
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            List<Tuple<string, string>> sparks = SerialPorts.ListPorts();

            if (sparks.Count < 1)
            {
                MessageBox.Show("Unable to find any Sparks to monitor.", "No Sparks", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (sparks.Count > 1)
            {
                MessageBox.Show("I can only monitor one Spark at a time.", "Too many Sparks", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            this.serialPort1.PortName = sparks[0].Item1;
            this.serialPort1.Open();
            this.btnStart.Enabled = false;
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            this.serialPort1.Close();
            this.btnStart.Enabled = true;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.serialPort1.IsOpen)
                this.serialPort1.Close();
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            if (e.EventType == System.IO.Ports.SerialData.Chars)
            {
                byte[] buffer = new byte[this.serialPort1.BytesToRead];

                this.serialPort1.Read(buffer, 0, this.serialPort1.BytesToRead);

                string receivedData = Encoding.ASCII.GetString(buffer);

                this.serialPortText.Invoke((MethodInvoker)delegate { this.serialPortText.AppendText(receivedData); });
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.serialPortText.Clear();
        }
    }
}
